<template>
  <div class="container">
    <!-- 数据看板 -->
    <el-row :gutter="20" class="dashboard">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="card-header">
              <span>总收入</span>
            </div>
          </template>
          <div class="stat-value">¥{{ totalRevenue.toFixed(2) }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="card-header">
              <span>总订单量</span>
            </div>
          </template>
          <div class="stat-value">{{ totalOrderCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="card-header">
              <span>平均客单价</span>
            </div>
          </template>
          <div class="stat-value">¥{{ avgPrice}}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表容器 -->
    <div ref="chart" class="chart-box"></div>

    <!-- 统计粒度选择 -->
    <div class="filter-box">
      <el-select
        v-model="timeGranularity"
        @change="fetchData"
        placeholder="选择统计方式"
        size="medium"
      >
        <el-option label="按日统计" value="day"/>
        <el-option label="按周统计" value="week"/>
        <el-option label="按月统计" value="month"/>
      </el-select>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElLoading } from 'element-plus'
import api from '@/api'

// 响应式数据
const timeGranularity = ref('day')
const chartData = ref([])
const chart = ref(null)
const chartInstance = ref(null)

// 计算属性
const totalRevenue = computed(() =>
  chartData.value.reduce((sum, item) => sum + item.total_revenue, 0)
)
const totalOrderCount = computed(() =>
  chartData.value.reduce((sum, item) => sum + item.order_count, 0)
)
const avgPrice = computed(() => {
  const total = totalRevenue.value
  const count = totalOrderCount.value
  const result = total / count
  return result.toFixed(2)
})

// 生命周期
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance.value?.dispose()
})

// 图表初始化
const initChart = () => {
  chartInstance.value = echarts.init(chart.value)
  fetchData()
}

// 数据获取
const fetchData = async () => {
  const loading = ElLoading.service({ target: chart.value })
  try {
    const res = await api.getRevenueAnalysis({
      granularity: timeGranularity.value
    })
    chartData.value = res.data
    renderChart()
  } finally {
    loading.close()
  }
}

// 图表渲染
const renderChart = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const date = params[0].name
        const revenue = params[0].value.toFixed(2)
        const orders = params[1].value
        return `${date}<br>¥${revenue} / ${orders}笔`
      }
    },
    legend: {
      data: ['总收入', '订单量'],
      top: 10
    },
    grid: {
      top: 60,
      left: 50,
      right: 30,
      bottom: 30,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.map(item => formatPeriod(item.period)),
      axisLine: { lineStyle: { color: '#eee' } }
    },
    yAxis: [
      {
        type: 'value',
        name: '金额（元）',
        axisLine: { show: false },
        splitLine: { lineStyle: { type: 'dashed' } }
      },
      {
        type: 'value',
        name: '订单量',
        axisLine: { show: false },
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '总收入',
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        itemStyle: { color: '#67C23A' },
        lineStyle: { width: 2 },
        data: chartData.value.map(item => item.total_revenue)
      },
      {
        name: '订单量',
        type: 'bar',
        yAxisIndex: 1,
        itemStyle: {
          color: '#409EFF',
          borderRadius: [2, 2, 0, 0]
        },
        barWidth: '60%',
        data: chartData.value.map(item => item.order_count)
      }
    ]
  }
  chartInstance.value.setOption(option)
}

// 辅助函数
const formatPeriod = (period) => {
  if (timeGranularity.value === 'week') {
    return `第${period.split('-')[1]}周`
  }
  return period
}

const handleResize = () => {
  chartInstance.value?.resize()
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.dashboard {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: box-shadow 0.3s;
}

.stat-card:hover {
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.card-header {
  font-weight: 500;
  color: #606266;
}

.stat-value {
  font-size: 22px;
  font-weight: 600;
  color: #409EFF;
  text-align: center;
  padding: 15px 0;
}

.chart-box {
  height: 500px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.filter-box {
  margin-top: 20px;
  text-align: center;
}

.el-select {
  width: 200px;
}
</style>
